package com.roosterrobotics.replicant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.roosterrobotics.replicant.provider.ReplicantData;

import android.app.Activity;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;



public class SensorDetail extends Activity {

	private TextView mSensorName;
	private TextView mProcessedValue;
	private TextView mSensorUnits;
	private TextView mRawValue;

	private Button mProcessedButton;
	private Button mRawButton;
	private ContentProviderClient client;
	private ContentProvider provider;
	private String address;
	private Long port;
	private Long mSensorId;
	private String commName;
	private String devName;
	
	private static final String REPGETRAWSENSOR = "RepGetRawSensor";
	private static final String REPGETPROCSENSOR = "RepGetProcSensor";
	private static final String EOM = "#";
	
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
			
			Resources res = getResources();
		    client = getContentResolver().acquireContentProviderClient(ReplicantData.AUTHORITY);
		    provider = client.getLocalContentProvider();
			setContentView(R.layout.sensor_detail);
			setTitle(R.string.sensor_detail);
			
			mSensorName = (TextView) findViewById(R.id.sensorName);
			mProcessedValue = (TextView) findViewById(R.id.proccessedValue);
			mSensorUnits = (TextView) findViewById(R.id.sensorUnits);
			mRawValue = (TextView) findViewById(R.id.rawValue);
			
			mProcessedButton = (Button) findViewById(R.id.processedButton);
			mRawButton = (Button) findViewById(R.id.rawButton);
			
			mProcessedValue.setText("--");
			mRawValue.setText("--");
			
			Bundle extras = getIntent().getExtras();
			
			if (extras != null) {
				mSensorId = extras.getLong(ReplicantData.Sensors.SENSOR_INTERNAL_ID_COLUMN_NAME);
				mSensorName.setText(extras.getString(ReplicantData.Sensors.SENSOR_NAME_COLUMN_NAME));
				mSensorUnits.setText(extras.getString(ReplicantData.Sensors.SENSOR_UNITS_COLUMN_NAME));
				commName = extras.getString("CommunityName");
				devName = extras.getString("DeviceName");
				address = extras.getString(ReplicantData.Devices.DEVICE_ADDRESS_COLUMN_NAME);
				port = extras.getLong(ReplicantData.Devices.DEVICE_PORT_COLUMN_NAME);
			}
			
			mProcessedButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					new SensorNetworkMessenger(REPGETPROCSENSOR).execute(address, String.valueOf(port), REPGETPROCSENSOR + " " + commName + " " + devName + " myApp "  +  mSensorId + EOM);
				}
			});
			
			mRawButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					new SensorNetworkMessenger(REPGETRAWSENSOR).execute(address, String.valueOf(port), REPGETRAWSENSOR + " " + commName + " " + devName + " myApp " + mSensorId + EOM);
				}
			});
			
	 }
	 
	 
		private class SensorNetworkMessenger extends AsyncTask<String, Void, String> {
			PrintWriter out = null;
			BufferedReader in = null;
			Socket s = null;
			String msg;
			
			public SensorNetworkMessenger(String m) {
				super();
				msg = m;
			}
			
			protected String doInBackground(String...strings) {
				String buffer = "";
				char a;

				try {
					s = new Socket(strings[0], Long.decode(strings[1]).intValue());
					out = new PrintWriter(s.getOutputStream());
					in = new BufferedReader(new InputStreamReader(s.getInputStream()));
					
					while (in.ready()) {
						a  = (char) in.read();
					}	
					msg = strings[2];
					out.println(msg);
					out.flush();
					buffer = in.readLine();
					out.close();
					in.close();
					s.close();
					// If there isn't a response but the connection was established.
					if (buffer == null) {
						buffer = "Error: Device not responding";
					}
				} catch (NumberFormatException e) {
					buffer = "Exception: Address format incorrect";
					return buffer;
				} catch (UnknownHostException e) {
					buffer = "Exception: Unknown host";
					return buffer;
				} catch (IOException e) {
					buffer = "Exception: I/O Error";
					return buffer;
				}
				return buffer;
			}
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				
				if (msg.startsWith(REPGETRAWSENSOR)) {
					mRawValue.setText(R.string.checking);
				}
				else if(msg.startsWith(REPGETPROCSENSOR)) {
					mProcessedValue.setText(R.string.checking);
				}
				
			}
			
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if (result.startsWith("Error:") || result.startsWith("Exception:")) {
					Toast toast = Toast.makeText(SensorDetail.this, result, Toast.LENGTH_LONG);
					toast.show();
					if (msg.startsWith(REPGETRAWSENSOR)) {
						mRawValue.setText("--");
					}
					else if(msg.startsWith(REPGETPROCSENSOR)) {
						mProcessedValue.setText("--");
					}
				}
				else { 
					String tValue = result.substring(result.lastIndexOf(" ") + 1, result.lastIndexOf(EOM));

					if (msg.startsWith(REPGETRAWSENSOR)) {
					mRawValue.setText(tValue);
					}
					else if(msg.startsWith(REPGETPROCSENSOR)) {
						mProcessedValue.setText(tValue);
					}
				}
			}
		}
}
